"""
API处理器模块
包含主要的业务逻辑处理函数
"""

import time
import uuid
from datetime import datetime, timezone, timedelta
from fastapi import HTTPException
import logging

from ..services.ai_services import get_ai_service
from .image_processor import ImageProcessor
from .rule_checker import RuleChecker
from ..logging_config import log_violation

logger = logging.getLogger(__name__)

class APIHandler:
    """API处理器"""

    def __init__(self, config: dict, rules: dict):
        self.config = config
        self.rules = rules
        self.image_processor = ImageProcessor(config)
        self.rule_checker = RuleChecker(rules)
        self.ai_service = get_ai_service(config)

    async def process_url_image(self, image_url: str, analysis_cache):
        """处理URL图片"""
        request_id = str(uuid.uuid4())
        tz = timezone(timedelta(hours=8))
        timestamp = datetime.now(tz).strftime('%Y-%m-%dT%H:%M:%S+08:00')
        step_times = {}
        overall_start = time.time()

        # 检查缓存
        cached_result = analysis_cache.get(image_url)
        if cached_result:
            logger.info(f"Request ID: {request_id}, Cache HIT for URL: {image_url}")
            return cached_result

        logger.info(f"Request ID: {request_id}, Cache MISS for URL: {image_url}")

        try:
            # 下载和处理图片
            start_time = time.time()
            image_bytes = await self.image_processor.download_image(image_url)
            step_times['下载图片'] = time.time() - start_time

            start_time = time.time()
            processed_image_bytes = self.image_processor.process_image(image_bytes)
            step_times['图片预处理'] = time.time() - start_time

            # 获取OCR结果
            ocr_text = ""
            if hasattr(self.ai_service, 'ocr_service'):
                try:
                    ocr_result = await self.ai_service.ocr_service.analyze(processed_image_bytes)
                    ocr_text = ocr_result.strip()
                    logger.info(f"[规则检查] OCR识别文字: {ocr_text}")
                except Exception as e:
                    logger.warning(f"[规则检查] OCR识别失败: {e}")

            # AI服务分析
            start_time = time.time()
            image_analysis = await self.ai_service.analyze(processed_image_bytes)
            ai_analysis_time = time.time() - start_time
            step_times['AI服务分析'] = ai_analysis_time

            # 规则检查
            start_time = time.time()
            check_result_details = await self.rule_checker.check_rules(image_analysis, ocr_text)
            step_times['规则检查'] = time.time() - start_time

            step_times['总耗时'] = time.time() - overall_start
            logger.info(f"Request ID: {request_id}, Total processing time: {step_times['总耗时']:.2f}s")
            check_result_details['step_times'] = step_times

            # 生成响应
            response_data = self._generate_response(
                check_result_details, image_analysis, image_url, request_id, timestamp
            )

            # 缓存结果
            analysis_cache[image_url] = response_data

            return response_data

        except HTTPException as e:
            raise e
        except Exception as e:
            logger.error(f"Request ID: {request_id}, unhandled exception: {str(e)}")
            raise HTTPException(status_code=500, detail=f"处理请求失败: {str(e)}")

    async def process_upload_image(self, file_content: bytes, filename: str):
        """处理上传图片"""
        request_id = str(uuid.uuid4())
        tz = timezone(timedelta(hours=8))
        timestamp = datetime.now(tz).strftime('%Y-%m-%dT%H:%M:%S+08:00')
        step_times = {}
        overall_start = time.time()

        try:
            # 验证文件大小
            if len(file_content) > self.config['image_service']['max_file_size']:
                raise HTTPException(status_code=400, detail="文件大小超过限制")

            # 预处理图片
            step_start = time.time()
            processed_image_bytes = self.image_processor.process_image(file_content)
            step_times['图片预处理'] = time.time() - step_start

            # 获取OCR结果
            ocr_text = ""
            if hasattr(self.ai_service, 'ocr_service'):
                try:
                    ocr_result = await self.ai_service.ocr_service.analyze(processed_image_bytes)
                    ocr_text = ocr_result.strip()
                    logger.info(f"[规则检查] OCR识别文字: {ocr_text}")
                except Exception as e:
                    logger.warning(f"[规则检查] OCR识别失败: {e}")

            # AI服务分析
            step_start = time.time()
            analyzed_text = await self.ai_service.analyze(processed_image_bytes)
            step_times['AI服务分析'] = time.time() - step_start

            # 规则检查
            step_start = time.time()
            check_result_details = await self.rule_checker.check_rules(analyzed_text, ocr_text)
            step_times['规则检查'] = time.time() - step_start

            step_times['总耗时'] = time.time() - overall_start
            check_result_details['step_times'] = step_times

            # 生成响应
            response_data = self._generate_upload_response(
                check_result_details, analyzed_text, filename, request_id, timestamp
            )

            return response_data

        except HTTPException as e:
            raise e
        except Exception as e:
            logger.error(f"Request ID: {request_id}, upload check exception: {str(e)}")
            raise HTTPException(status_code=500, detail=f"处理上传文件失败: {str(e)}")

    def _generate_response(self, check_result_details, image_analysis, image_url, request_id, timestamp):
        """生成URL图片检查响应"""
        violated_rules = check_result_details['violated_rules']
        is_compliant = len(violated_rules) == 0

        if is_compliant:
            description = "未发现违规内容"
        else:
            description = self._generate_description(check_result_details)

        response_data = {
            "合规": is_compliant,
            "说明": description,
            "详细检查结果": check_result_details,
            "original_image_url": image_url,
            "request_id": request_id,
            "timestamp": timestamp
        }

        # 记录违规日志
        if not is_compliant:
            model_name = self.config.get('active_model', 'hybrid')
            log_violation(
                image_url=image_url,
                violation_reason=', '.join(violated_rules),
                model_name=model_name,
                model_output=image_analysis
            )

        return response_data

    def _generate_upload_response(self, check_result_details, analyzed_text, filename, request_id, timestamp):
        """生成文件上传检查响应"""
        violated_rules = check_result_details['violated_rules']
        is_compliant = len(violated_rules) == 0

        if is_compliant:
            description = "未发现违规内容"
        else:
            description = self._generate_description(check_result_details)

        response_data = {
            "合规": is_compliant,
            "说明": description,
            "详细检查结果": check_result_details,
            "original_filename": filename,
            "request_id": request_id,
            "timestamp": timestamp
        }

        # 记录违规日志
        if not is_compliant:
            model_name = self.config.get('active_model', 'hybrid')
            log_violation(
                image_url=f"上传文件: {filename}",
                violation_reason=', '.join(violated_rules),
                model_name=model_name,
                model_output=analyzed_text
            )

        return response_data

    def _generate_description(self, check_result_details):
        """生成违规描述"""
        violated_rules = check_result_details['violated_rules']
        detection_sources = check_result_details.get('detection_sources', {})
        ocr_text = check_result_details.get('ocr_text', '')

        description_parts = []
        description_parts.append(f"在图片中发现违规内容: {', '.join(violated_rules)}")

        if ocr_text:
            description_parts.append(f" {ocr_text}")

        # 添加检测源信息
        for rule_name, sources in detection_sources.items():
            source_info = []
            if sources.get('ocr_text'):
                source_info.append("OCR文字")
            if sources.get('ai_description'):
                source_info.append("AI描述")
            if sources.get('quoted_content'):
                source_info.append("引号内容")

            if source_info:
                description_parts.append(f"{rule_name}检测自: {', '.join(source_info)}")

        return " | ".join(description_parts)
